package cn.flying.cloud.system.dict.service.impl;

import javax.annotation.Resource;

import java.io.InputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.flying.cloud.base.common.exception.BizException;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.PageRequest;
import cn.flying.cloud.base.common.vo.PageResponse;
import cn.flying.cloud.common.enums.StatusEnum;
import cn.flying.cloud.system.dict.entity.SysDictData;
import cn.flying.cloud.system.dict.entity.SysDictType;
import cn.flying.cloud.system.dict.mapper.SysDictTypeMapper;
import cn.flying.cloud.system.dict.model.SysDict;
import cn.flying.cloud.system.dict.service.SysDictDataService;
import cn.flying.cloud.system.dict.service.SysDictTypeService;

/**
 * <p>
 * 枚举字段类型表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-04-02 13:05:17
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SysDictDataService sysDictDataService;

    /**
     * 分页查询枚举字段类型表数据
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<SysDictType> getPageList(PageRequest<SysDictType> request) {
        SysDictType param = request.getParam();
        LambdaQueryWrapper<SysDictType> wrapper = getLambdaQueryWrapper(param);
        wrapper.orderByDesc(SysDictType::getCreatedTime);
        Page<SysDictType> page = this.page(new Page<>(request.getPageNum(), request.getPageSize()), wrapper);
        return new PageResponse<>(page.getTotal(), (int) page.getCurrent(), page.getRecords());
    }

    /**
     * 构建查询对象
     *
     * @param param
     * @return
     */
    private LambdaQueryWrapper<SysDictType> getLambdaQueryWrapper(SysDictType param) {
        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();
        if (param != null) {
            if (Ft.String.isNotBlank(param.getDictType())) {
                wrapper.eq(SysDictType::getDictType, param.getDictType());
            }
            if (Ft.String.isNotBlank(param.getDictDesc())) {
                wrapper.like(SysDictType::getDictDesc, "%" + param.getDictDesc() + "%");
            }
            if (Ft.String.isNotBlank(param.getStatus())) {
                wrapper.eq(SysDictType::getStatus, param.getStatus());
            }
        }
        return wrapper;
    }

    /**
     * 列表查询枚举字段类型表数据
     *
     * @param sysDictType
     * @return
     */
    @Override
    public List<SysDictType> getList(SysDictType sysDictType) {
        LambdaQueryWrapper<SysDictType> wrapper = getLambdaQueryWrapper(sysDictType);
        List<SysDictType> list = this.list(wrapper);
        return list;
    }

    /**
     * 查询枚举字段类型表详情数据
     *
     * @param sysDictType
     * @return
     */
    @Override
    public SysDictType getOneObj(SysDictType sysDictType) {
        LambdaQueryWrapper<SysDictType> wrapper = getLambdaQueryWrapper(sysDictType);
        return this.getOne(wrapper);
    }


    /**
     * 新增枚举字段类型表数据
     *
     * @param sysDictType
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createObj(SysDictType sysDictType) {
        return this.save(sysDictType);
    }

    /**
     * 更新枚举字段类型表数据
     *
     * @param sysDictType
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateObj(SysDictType sysDictType) {
        return this.saveOrUpdate(sysDictType);
    }

    /**
     * 删除枚举字段类型表数据
     *
     * @param sysDictType
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteObj(SysDictType sysDictType) {
        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictType::getDictType, sysDictType.getDictType());
        boolean removed = this.remove(wrapper);

        LambdaQueryWrapper<SysDictData> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysDictData::getDictType, sysDictType.getDictType());
        sysDictDataService.remove(wrapper1);

        return removed;
    }

    /**
     * 根据Id删除
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Serializable id) {
        return this.removeById(id);
    }

    /**
     * 导入Excel
     *
     * @param file
     */
    @Override
    public void importExcel(MultipartFile file) throws Exception {
        try (InputStream inputStream = file.getInputStream()) {
            List<SysDict> dicts = Ft.Excel.readExcel(inputStream, SysDict.class, 0, 1);
            if (CollectionUtils.isEmpty(dicts)) {
                return;
            }
            Map<String, List<SysDict>> map = dicts.stream().collect(Collectors.groupingBy(SysDict::getDictType));
            map.forEach((k, list) -> {
                LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysDictType::getDictType, k);
                SysDictType sysDictType = this.getOne(wrapper);
                if (sysDictType == null) {
                    SysDict sysDict = list.get(0);

                    SysDictType dictType = new SysDictType();
                    dictType.setDictType(sysDict.getDictType().trim());
                    dictType.setDictDesc(sysDict.getDictDesc().trim());
                    dictType.setStatus(StatusEnum.STATUS_Y.getCode());
                    dictType.setTenantId(Ft.Local.TenantId());

                    this.save(dictType);
                }

                List<SysDictData> data = list.stream().map(sysDict -> {
                    SysDictData sysDictData = new SysDictData();
                    sysDictData.setCode(sysDict.getCode().trim());
                    sysDictData.setText(sysDict.getText().trim());
                    sysDictData.setDictType(sysDict.getDictType().trim());
                    sysDictData.setDictDesc(sysDict.getDictDesc().trim());
                    sysDictData.setStatus(StatusEnum.STATUS_Y.getCode());
                    sysDictData.setTenantId(Ft.Local.TenantId());

                    return sysDictData;
                }).collect(Collectors.toList());
                sysDictDataService.saveBatch(data);
            });

        } catch (Exception e) {
            throw new BizException("解析Excel保存失败--->", e);
        }
    }
}
